namespace Fsharp.wpf

module Xaml =
    open System
    open System.IO
    open System.Windows
    open System.Windows.Markup
    open System.Xml
    open System.Windows.Media
    open System.Windows.Data
    open System.Windows.Controls

    /// 从XAML字符串创建对象
    let fromString<'T> (xaml: string) : 'T =
        use reader = new StringReader(xaml)
        use xmlReader = XmlReader.Create(reader)
        Markup.XamlReader.Load(xmlReader) :?> 'T

    /// 从XAML文件创建对象
    let fromFile<'T> (filePath: string) : 'T =
        if not (File.Exists(filePath)) then
            raise (FileNotFoundException(sprintf "XAML文件未找到: %s" filePath))
        File.ReadAllText(filePath) |> fromString<'T>

    /// 从资源创建对象
    let fromResource<'T> (resourcePath: string) : 'T =
        let uri = new Uri(resourcePath, UriKind.Relative)
        Application.LoadComponent(uri) :?> 'T

    /// 绑定功能
    module Binding =
        let create path source mode =
            new Binding(path, Source = source, Mode = mode)

        let setDataContext (element: FrameworkElement) (dataContext: obj) =
            element.DataContext <- dataContext

    /// 编写一个函数，根据元素名称查找元素
    let findElementByName (parent: DependencyObject) (name: string) : DependencyObject option =
        let rec findChild (parent: DependencyObject) (name: string) : DependencyObject option =
            [0..VisualTreeHelper.GetChildrenCount(parent)-1]
            |> List.tryPick (fun i ->
                let child = VisualTreeHelper.GetChild(parent, i)
                match child with
                | :? FrameworkElement as fe when fe.Name = name -> Some fe
                | _ -> findChild child name)
        findChild parent name